package top_request

import (
	"encoding/json"
	"fmt"
	"gitee.com/ha666/golibs"
	"net/url"
	"strings"
	"top_sdk"
	"top_sdk/top_model"
)

func AuthTokenRefresh(refresh_session string) (top_auth_token top_model.TopAuthToken, err_msg string) {
	params := top_system_params()
	params.Set("method", "taobao.top.auth.token.refresh")
	params.Set("refresh_token", refresh_session)
	params.Set("sign", top_sign(params, top_sdk.Tao_APP_SECRET))
	_, resp_body, err := golibs.Post(top_sdk.Tao_API_HTTPS_URL, params)
	if err != nil {
		return top_auth_token, err.Error()
	}
	if strings.Contains(resp_body, "error_response") {
		top_error_response := &top_model.TopErrorResponse{}
		err = json.Unmarshal([]byte(resp_body), &top_error_response)
		if err != nil {
			return top_auth_token, err.Error()
		}
		return top_auth_token, fmt.Sprintf("%d,%s,%s,%s", top_error_response.ErrorResponse.Code, top_error_response.ErrorResponse.Msg, top_error_response.ErrorResponse.SubCode, top_error_response.ErrorResponse.SubMsg)
	} else {
		var result top_model.TopAuthTokenRefreshResult
		err = json.Unmarshal([]byte(resp_body), &result)
		if err != nil {
			return top_auth_token, err.Error()
		}
		resp_body = result.TopAuthTokenRefreshResponse.TokenResult
		err = json.Unmarshal([]byte(resp_body), &top_auth_token)
		if err != nil {
			return top_auth_token, err.Error()
		}
		if len(top_auth_token.AccessToken) < 32 {
			return top_auth_token, "解析结果出错"
		}
		top_auth_token.TaobaoUserNick, err = url.PathUnescape(top_auth_token.TaobaoUserNick)
		if err != nil {
			return top_auth_token, err.Error()
		}
		if len(top_auth_token.SubTaobaoUserNick) > 0 {
			top_auth_token.SubTaobaoUserNick, err = url.PathUnescape(top_auth_token.SubTaobaoUserNick)
			if err != nil {
				return top_auth_token, err.Error()
			}
		}
		return top_auth_token, ""
	}
}
